const SECOND = 1000;

const vm = new Vue({
    el: '#main',
    data: {
        msg: '',
        fromId: fxj.getSearch().get('landlordId'),
        houseId: fxj.getSearch().get('houseId'),
        sendAble: false,
        chatList: [],
        type: fxj.getSearch().get('type'),
    },
    methods: {
        send,
        hasContent,
        removeBorder,
    },
    mounted() {},
});


function apiready() {
    fxj.fixLayout();
    reqChatList();
    listenMsg(SECOND * 5);
    initInput();
}

function initInput() {
    var inputField = api.require('inputField');
    inputField.open({
        bgColor: '#f2f2f2',
        lineColor: 'rgba(0,0,0,.2)',
        fileBgColor: '#fff',
        borderColor: '#fff',
        fixedOn: api.frameName,
        maxLines: 3,
        sendBtn: {
            bg: '#ff8c02', //字符串类型；发送按钮常态背景色
            bgHighlight: '#ff5100', //字符串类型；发送按钮点击时的高亮背景色
            title: '发送', //字符串类型；发送按钮的标题
            titleSize: 12, //数字类型；发送按钮的标题字体大小
            titleColor: '#fff', //字符串类型；发送按钮标题文字颜色
            corner: 5,
        },
    }, function (ret) {
        if (ret) {
            const msg = ret.msg;
            send(msg);
        }
    });
}

async function reqChatList(close) {
    const res = await ajax({
        url: 'home/chat/getContent',
        data: {
            fromId: vm.fromId,
        },
    });
    if (typeof close === 'function') {
        close();
    }
    if (res.err === 0) {
        if (res.data == null) return;
        res.data.sort((a, b) => {
            return Number(a.date) - Number(b.date);
        });
        forEach(res.data, chat => {
            chat.date = new Date(Number(chat.date + '000')).toLocaleString();
        });
        if (vm.chatList.length !== res.data.length) {
            setTimeout(() => {
                window.scrollTo(0, document.body.scrollHeight);
            }, 0);
        }
        vm.chatList = res.data;
    }
}

async function send(msg) {
    if (!msg) {
        toast('信息不能为空');
        return;
    }
    const close = fxj.dialog.loading({
        noBg: true
    });
    const res = await ajax({
        url: 'home/chat/sendMsg',
        data: {
            msg,
            toId: vm.fromId,
            houseId: vm.houseId,
        },
    });
    if (res.err === 0) {
        vm.msg = '';
        vm.sendAble = false;
        reqChatList(close);
    }
}

function hasContent(evt) {
    vm.sendAble = !!vm.msg;
    if (evt.keyCode === 13) {
        send();
    }
}

function listenMsg(s) {
    setInterval(() => {
        reqChatList();
    }, s);
}

function removeBorder(evt) {
    const target = evt.target;
    target.classList.remove('border');
}